extends Control

@onready var card_back_ground = $CardBackGround
@onready var shadow = $Shadow

@onready var card_audio = $CardAudio
@onready var card_run_audio = $CardRunAudio

@onready var idle_timer = $IdleTimer
@onready var for_show_some_detail = $ForShowSomeDetail

@onready var func_card_img = $CardBackGround/FuncCardImg


@export var card_name:String = "功能牌" # 名字
@export var trigger_timing = 1 #1-->回合开始， 2-->单次出牌结算中， 3-->单次出牌结算后， 4-->回合结束
@export var cost = 1
@export var card_id = "Base"
@export var self_description:String = "这是一段描述文字" # 功能介绍
@export var can_hybridization = true #能否杂交

func cardFunction():
	await FunctionCardFuncMapping.call_method_by_id(self)
	await FunctionCardFuncMapping.call_method_by_add_id(self)

#=====================以下Base固定=====================#
#用于旋转的动画效果
var tween_rot : Tween
#Card Y轴旋转最大角度
@export var angle_x_max = 20
#Card X轴旋转最大角度
@export var angle_y_max = 25
#阴影便宜量
@export var max_offset_shadow = 10
#是否播放音乐
var play_audio_flag = true
#鼠标是否在卡牌上
var is_on_card = false

func _init()-> void:
	#将角度转为弧度
	angle_x_max = deg_to_rad(angle_x_max)
	angle_y_max = deg_to_rad(angle_y_max)

func _process(delta: float) -> void:
	#鼠标不在卡牌上时，自由摆动
	_on_idle_timer_timeout(delta)

#鼠标移入事件
func _on_gui_input(event: InputEvent) -> void:
	if not event is InputEventMouseMotion : return
	#鼠标在卡牌上
	is_on_card = true
	#开始播放音频，将flag设置为false
	if not card_audio.playing && play_audio_flag:
		card_audio.play()
	play_audio_flag = false
	#获取鼠标位置
	var mouse_pos = get_local_mouse_position()
	#将位置映射到0-1
	var lerp_val_x = remap(mouse_pos.x,0,size.x,0,1)
	var lerp_val_y = remap(mouse_pos.y,0,size.y,0,1)
	#以弧度表示的角度转换为度
	var x_rot = rad_to_deg(lerp_angle(-angle_x_max,angle_x_max,lerp_val_x))
	var y_rot = rad_to_deg(lerp_angle(-angle_y_max,angle_y_max,lerp_val_y))
	#设置卡牌shader参数
	card_back_ground.material.set_shader_parameter("x_rot",x_rot)
	card_back_ground.material.set_shader_parameter("y_rot",y_rot)

#鼠标移入事件
func _on_mouse_entered() -> void:
	#展示卡牌详细
	showForDescription()

#鼠标移出事件
func _on_mouse_exited() -> void:
	#停止播放音频，将flag设置为true
	card_audio.stop()
	play_audio_flag = true
	#将卡牌平滑的恢复0角度
	if tween_rot and tween_rot.is_running():
		tween_rot.kill()
	tween_rot = create_tween().set_ease(Tween.EASE_OUT).set_trans(Tween.TRANS_BACK).set_parallel(true)
	
	tween_rot.tween_property(card_back_ground.material,"shader_parameter/y_rot",0,0.5)
	#隐藏卡牌详细
	var root = get_tree().current_scene.get_children()[0]
	var for_description = root.get_node("ForDescription")
	if for_description:
		for_description.visible = false
	#鼠标不在卡牌上
	if tween_rot.finished:
		is_on_card = false

#idle状态下卡牌自由摆动
var idle_time := 0.0
var idle_amplitude_x := 15.0  # 最大摆动角度（单位：度）
var idle_amplitude_y := 10.0
var idle_speed := 1.0        # 控制摆动速度
func _on_idle_timer_timeout(delta) -> void:
	if is_on_card : return
	#随机角度
	idle_time += delta * idle_speed

	var x_rot = idle_amplitude_x * sin(idle_time)
	var y_rot = idle_amplitude_y * sin(idle_time * 1.2)

	card_back_ground.material.set_shader_parameter("x_rot", x_rot)
	card_back_ground.material.set_shader_parameter("y_rot", y_rot)

#展示卡牌详细
func showForDescription():
	var root = get_tree().current_scene.get_children()[0]
	var for_description = root.get_node("ForDescription")
	if for_description:
		var name = for_description.get_child(0)
		name.text = card_name
		var description = for_description.get_child(1)
		description.text = self_description
		var forHybridization = for_description.get_child(2)
		if FunctionCardStrongLevel.addCardArr[card_id].size() > 0:
			var str = "杂交："
			for i in FunctionCardStrongLevel.addCardArr[card_id]:
				var functionCardName = FunctionCardStrongLevel.funcCardName[i]
				var addStr = " " + functionCardName + " "
				str += addStr
			forHybridization.text = str
		else:
			var str = ""
			for i in FunctionCardStrongLevel.addCardArr[card_id]:
				var functionCardName = FunctionCardStrongLevel.funcCardName[i]
				var addStr = " " + functionCardName + " "
				str += addStr
			forHybridization.text = str
		for_description.visible = true

#当卡牌被调用时的特效
func functionCardShake(control_node: Control, angle := 15, duration := 0.1):
	#播放音效
	card_run_audio.play()
	
	#动画特效
	#将index调高
	control_node.z_index = 999
	var original_rotation = control_node.rotation_degrees
	# 设置旋转中心为节点中心
	control_node.pivot_offset = control_node.size * 0.5
	# 顺时针转15°
	control_node.rotation_degrees = original_rotation + angle
	control_node.scale = Vector2(1.2,1.2)
	var root = get_tree().current_scene.get_children()[0]
	var func_card_run_timer = root.get_node("FuncCardRunTimer")
	if func_card_run_timer:
		func_card_run_timer.start()
		await func_card_run_timer.timeout
	control_node.scale = Vector2(1.0,1.0)
	# 转回原位
	control_node.rotation_degrees = original_rotation
	control_node.z_index = 0

#抖动特效
func shakeTween(funcCardInstance):
	var original_rotation = funcCardInstance.rotation_degrees
	for i in range(8):
		#右摆
		funcCardInstance.pivot_offset = funcCardInstance.size * 0.5
		funcCardInstance.rotation_degrees = original_rotation + 15
		funcCardInstance.scale = Vector2(1.1,1.1)
		await get_tree().create_timer(0.01).timeout  # 等待0.1s
		# 转回原位
		funcCardInstance.scale = Vector2(1.0,1.0)
		funcCardInstance.rotation_degrees = original_rotation
		await get_tree().create_timer(0.01).timeout  # 等待0.1s
		#左摆
		funcCardInstance.rotation_degrees = original_rotation - 15
		funcCardInstance.scale = Vector2(1.1,1.1)
		await get_tree().create_timer(0.01).timeout  # 等待0.1s
		# 转回原位
		funcCardInstance.scale = Vector2(1.0,1.0)
		funcCardInstance.rotation_degrees = original_rotation
		await get_tree().create_timer(0.01).timeout  # 等待0.1s

#逐渐消失
func dieTween(funcCardInstance):
	tween_rot = create_tween().set_ease(Tween.EASE_OUT).set_trans(Tween.TRANS_BACK).set_parallel(false)
	tween_rot.tween_property(funcCardInstance, "modulate", Color(1, 1, 1, 0), 1)
